package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.heima.file.service.FileStorageService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper,WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.endpoint}")
    String endpoint;
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }

        // 2 上传到oss
        String fileId = null;
        try {
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String sufix = originalFilename.substring(originalFilename.lastIndexOf("."));

        fileId = fileStorageService.store(profix,fileName+sufix,multipartFile.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        wmMaterial.setUrl(webSite+fileId);
        return ResponseResult.okResult(wmMaterial);
    }


    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
        .set(WmMaterial::getIsCollection,type)
        .eq(WmMaterial::getUserId,id)
        .eq(WmMaterial::getId,uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if(id==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if(count>0){
            throw new CustomException( AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
        //删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        // 删除素材库
        removeById(id);
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();

        if(wmUser==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        lambdaQueryWrapper.eq(WmMaterial::getUserId,wmUser.getId());
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> iPage =new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(iPage, lambdaQueryWrapper);

        List<WmMaterial> wmMaterials = resultPage.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultPage.getTotal());
        pageResponseResult.setData(wmMaterials);
        return pageResponseResult;
    }

}
